import { SubscribeMessage, WebSocketGateway } from "@nestjs/websockets";
import { configuration } from "../../../../config/config";
import { tap } from "rxjs";
import { EnumMicroService, SysIntervalMsgType } from "../../../../types/types";
import { NatsClientService } from "@app/nats-client";
import { ConnectStateService } from "../share/connect-state/connect-state.service";

@WebSocketGateway(configuration.gateway.socket_io_port, {
  namespace: configuration.gateway.socket_io_namespace,
})
export class WsGateway {
  private clientMap = new Map();

  constructor(
    private readonly natsGatewayClient: NatsClientService,
    private readonly connectStateService: ConnectStateService,
  ) {
    const observer = this.connectStateService.onConnectionChange();
    observer.subscribe((state) => {
      this.sendMsg({
        toClientId: null,
        type: "gateway",
        msg: state,
      });
    });
  }

  handleConnection(client: any) {
    this.clientMap.set(client.id, client);
    console.log("Client connected:", client.id);
    this.connectStateService.connectFE();
  }

  handleDisconnect(client: any) {
    this.clientMap.delete(client.id);
    this.connectStateService.disconnectFE();
  }

  // 如果指定了客户端就向指定客户端发送，否则就广播。
  sendMsg({ toClientId = null, type, msg }) {
    if (toClientId === null && this.clientMap.size > 0) {
      for (const clientId of this.clientMap.keys()) {
        const client = this.clientMap.get(clientId);
        console.log("client", clientId, type,JSON.stringify(msg));
        client.emit(type, msg);
      }
      return;
    }
    const client = this.clientMap.get(toClientId);
    if (client) {
      client.emit(type, msg);
    }
  }

  /*订阅前端发送来的消息，分发给不同的系统。*/
  @SubscribeMessage(SysIntervalMsgType.FE_GATEWAY_EXCHANGE_EVENT)
  async handleMessage(client: any, payload: any) {
    const { systemType, ...data } = JSON.parse(payload);
    // console.log("收到前端发送的，socket io消息", `消息发送的系统是：${systemType}`,JSON.stringify(data));
    Object.assign(data, {
      extra: {
        clientId: client.id,
      },
    });
    let event: SysIntervalMsgType;
    switch (systemType) {
      case EnumMicroService.system:
        event = SysIntervalMsgType.SYSTEM_MSG_EVENT;
        break;
      case EnumMicroService.dicom:
        event = SysIntervalMsgType.DICOM_MSG_EVENT;
        break;
      case EnumMicroService.image:
        event = SysIntervalMsgType.IMAGE_MSG_EVENT;
        break;
      default:
        break;
    }
    return this.natsGatewayClient.send(event, data).pipe(
      tap((response) => {
        client.emit(systemType, response);
      }),
    );
  }
}
